var api = require('../../utils/api.js');

Page({
  data: {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    currentDate: '',
    weekdays: ['日', '一', '二', '三', '四', '五', '六'],
    calendarDays: [],
    emotionColors: [
      { color: '#ff6b6b', label: '红 - 兴奋/满足/开心/高兴' },
      { color: '#ffa726', label: '橙 - 自信/平静/愉悦' },
      { color: '#42a5f5', label: '蓝 - 焦虑/悲伤/内疚/共情' },
      { color: '#66bb6a', label: '绿 - 愤怒/恐惧/失望' },
      { color: '#9e9e9e', label: '灰 - 无记录' }
    ],
    colorMap: {
      '红': '#ff6b6b',
      '橙': '#ffa726', 
      '蓝': '#42a5f5',
      '绿': '#66bb6a',
      '灰': '#9e9e9e'
    },
    warmMessages: [
      "每一天都是新的开始，记录情绪是关爱自己的第一步 ",
      "情绪没有对错，接纳它们就是接纳真实的自己",
      "你的感受很重要，每一刻都值得被温柔对待 ",
      "情绪是内心的信使，倾听它们的声音 ",
      "每一个情绪都是成长路上的风景，让我们一起温柔前行 ",
      "记录情绪，就是给自己的内心一个温暖的拥抱 ",
      "情绪如四季更替，每一个都有它独特的美 ",
      "你的情绪日记，是内心最真实的独白 ",
      "每一天的情绪都是生命的色彩，让它们绽放光彩 ",
      "温柔地对待自己的情绪，就是最大的自爱 "
    ],
    warmMessage: '',
    loading: false
  },

  onLoad: function() {
    this.setCurrentDate();
    this.generateCalendar();
    this.loadEmotionCalendar();
    this.setRandomMessage();
  },

  onShow: function() {
    // 每次显示页面时重新加载数据
    this.loadEmotionCalendar();
  },

  setCurrentDate: function() {
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    this.setData({
      year: year,
      month: month,
      currentDate: year + '-' + (month < 10 ? '0' + month : month)
    });
  },

  setRandomMessage: function() {
    var messages = this.data.warmMessages;
    var randomIndex = Math.floor(Math.random() * messages.length);
    this.setData({
      warmMessage: messages[randomIndex]
    });
  },

  prevMonth: function() {
    var year = this.data.year;
    var month = this.data.month;
    
    if (month === 1) {
      year--;
      month = 12;
    } else {
      month--;
    }
    
    this.setData({
      year: year,
      month: month,
      currentDate: year + '-' + (month < 10 ? '0' + month : month)
    });

    this.generateCalendar();
    this.loadEmotionCalendar();
  },

  nextMonth: function() {
    var year = this.data.year;
    var month = this.data.month;
    
    if (month === 12) {
      year++;
      month = 1;
    } else {
      month++;
    }
    
    this.setData({
      year: year,
      month: month,
      currentDate: year + '-' + (month < 10 ? '0' + month : month)
    });

    this.generateCalendar();
    this.loadEmotionCalendar();
  },

  onDateChange: function(e) {
    var dateStr = e.detail.value;
    var dateParts = dateStr.split('-');
    var year = parseInt(dateParts[0]);
    var month = parseInt(dateParts[1]);
    
    this.setData({
      year: year,
      month: month,
      currentDate: dateStr
    });

    this.generateCalendar();
    this.loadEmotionCalendar();
  },

  generateCalendar: function() {
    var year = this.data.year;
    var month = this.data.month;
    var firstDay = new Date(year, month - 1, 1);
    var lastDay = new Date(year, month, 0);
    var startDate = new Date(firstDay);
    var endDate = new Date(lastDay);

    // 调整到日历开始（周日）
    var dayOfWeek = firstDay.getDay();
    startDate.setDate(startDate.getDate() - dayOfWeek);

    // 调整到日历结束（周六）
    var endDayOfWeek = lastDay.getDay();
    endDate.setDate(endDate.getDate() + (6 - endDayOfWeek));

    var calendarDays = [];
    var currentDate = new Date(startDate);
    var today = new Date();

    while (currentDate <= endDate) {
      var isCurrentMonth = currentDate.getMonth() === month - 1;
      var isToday = currentDate.toDateString() === today.toDateString();
      
      // 修复日期格式，使用本地时间
      var dateStr = this.formatDate(currentDate);
      
      calendarDays.push({
        date: dateStr,
        day: currentDate.getDate(),
        isCurrentMonth: isCurrentMonth,
        isToday: isToday,
        hasRecord: false,
        emotionColor: null,
        colorValue: null
      });

      currentDate.setDate(currentDate.getDate() + 1);
    }

    this.setData({ calendarDays: calendarDays });
  },

  formatDate: function(date) {
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString().padStart(2, '0');
    var day = date.getDate().toString().padStart(2, '0');
    return year + '-' + month + '-' + day;
  },

  loadEmotionCalendar: function() {
    var that = this;
    if (this.data.loading) return;

    this.setData({ loading: true });

    api.getEmotionCalendar(this.data.year, this.data.month).then(function(response) {
      console.log('情绪日历响应:', response);
      if (response.code === 200 && response.data && response.data.calendar) {
        var calendarData = response.data.calendar;
        var updatedDays = that.data.calendarDays.map(function(day) {
          var dayData = null;
          for (var i = 0; i < calendarData.length; i++) {
            if (calendarData[i].date === day.date) {
              dayData = calendarData[i];
              break;
            }
          }
          
          if (dayData) {
            var emotionColor = dayData['emotion-colour'];
            // 修改逻辑：所有有颜色数据的日期都认为有记录
            var hasRecord = emotionColor && emotionColor !== '';
            var colorValue = that.data.colorMap[emotionColor] || '#9e9e9e';
            
            return {
              date: day.date,
              day: day.day,
              isCurrentMonth: day.isCurrentMonth,
              isToday: day.isToday,
              hasRecord: hasRecord,
              emotionColor: emotionColor,
              colorValue: colorValue
            };
          }
          return day;
        });

        that.setData({ calendarDays: updatedDays });
        console.log('更新后的日历数据:', updatedDays);
      }
    }).catch(function(error) {
      console.error('加载情绪日历失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }).finally(function() {
      that.setData({ loading: false });
    });
  },

  onDayTap: function(e) {
    console.log('点击日期:', e.currentTarget.dataset);
    
    var date = e.currentTarget.dataset.date;
    var hasRecord = e.currentTarget.dataset.hasRecord;
    
    // 解析点击的具体日期
    var dateParts = date.split('-');
    var clickedYear = parseInt(dateParts[0]);
    var clickedMonth = parseInt(dateParts[1]);
    var clickedDay = parseInt(dateParts[2]);
    
    console.log('点击的具体日期:', {
      year: clickedYear,
      month: clickedMonth,
      day: clickedDay,
      hasRecord: hasRecord
    });
    
    // 验证日期
    if (!date || !clickedYear || !clickedMonth || !clickedDay) {
      console.error('日期参数无效:', { date, clickedYear, clickedMonth, clickedDay });
      return;
    }
    
    // 验证月份范围
    if (clickedMonth < 1 || clickedMonth > 12) {
      console.error('月份超出范围:', clickedMonth);
      return;
    }
    
    // 检查是否是当前月份
    var isCurrentMonth = clickedMonth === this.data.month && clickedYear === this.data.year;
    
    // 构建URL - 使用点击的具体日期
    var url = '/pages/emotion-list/emotion-list?year=' + clickedYear + 
              '&month=' + clickedMonth + 
              '&selectedDate=' + date + 
              '&hasRecord=' + hasRecord + 
              '&isCurrentMonth=' + isCurrentMonth;
    
    console.log('跳转URL:', url);
    
    // 如果有记录，跳转到情绪列表
    if (hasRecord === 'true' || hasRecord === true) {
      wx.navigateTo({
        url: url,
        success: function() {
          console.log('跳转到情绪列表成功');
        },
        fail: function(error) {
          console.error('跳转失败:', error);
        }
      });
    } else {
      // 如果没有记录，可以选择显示提示或者跳转到添加情绪页面
      wx.showModal({
        title: '暂无记录',
        content: '这一天还没有情绪记录，是否要添加一条？',
        confirmText: '添加',
        cancelText: '取消',
        success: function(res) {
          if (res.confirm) {
            // 跳转到添加情绪页面
            wx.navigateTo({
              url: '/pages/add-emotion/add-emotion?date=' + date
            });
          }
        }
      });
    }
  }
});